﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;

namespace ObTookit.Auto
{
    public class DocCoder:BaseCoder
    {
        public string CreateCode()
        {
            FieldObject pkFO = GetIdObject();

            string text = ReadTemplate(Template);
            text = text.Replace("[#AUTHOR#]", Author);
            text = text.Replace("[#CREATED#]", CreateDate);
            text = text.Replace("[#ClsName#]", AutoObj.ClsName);
            text = text.Replace("[#tbDescri#]", AutoObj.TbDescri);
            text = text.Replace("[#docFields#]", CreateDocFields());

            text = text.Replace("[#sClsName#]", StringUtil.FirstChar(AutoObj.ClsName, "_", false));

            text = text.Replace("[#IdAlias#]", pkFO.Alias);
            text = text.Replace("[#PkType#]", pkFO.DbType);
            text = text.Replace("[#PkDescri#]", pkFO.Descr);

            text = text.Replace("[#ClsFields#]", CreateFields());

            return text;
        }

        private string CreateDocFields()
        {
            StringBuilder sb = new StringBuilder();
            foreach(FieldObject fo in FieldObjs) 
            {
                sb.Append(fo.Alias + CodeArgs.TAB);
                string type = fo.DbType ?? "";
                switch (type.ToUpper())
                {
                    case "VARCHAR":
                        type = "string";
                        break;
                    case "BIT":
                        type = "bool";
                        break;
                    default:
                        break;
                }
                sb.Append(type.ToLower() + CodeArgs.TAB);
                sb.Append(CodeArgs.TAB3);
                sb.Append(fo.Descr + CodeArgs.RN);
            }
            return sb.Remove(sb.Length - 1, 1).ToString();
        }

        private string CreateFields()
        {
            StringBuilder sb = new StringBuilder();
            foreach (FieldObject fo in FieldObjs)
            {
                sb.Append(fo.Alias);
                sb.Append(",");
            }
            return sb.Remove(sb.Length - 1, 1).ToString();
        }
    }
}
